import { makeObservable, action, observable, computed } from "mobx";
import { todoType } from "../model";

class todoStore {
    constructor() {
        // 加上这个调用action方法时保证this是指向store的
        makeObservable(this);
    }
    // loading
    @observable loading: boolean = true;
    // 所有todos
    @observable allTodos: todoType[] = [
        {id:1, text:'todo1', finished:true },
        {id:2, text:'todo2', finished:true },
        {id:3, text:'todo3', finished:false },
        {id:4, text:'todo4', finished:false },
    ]
    // 搜索关键字
    @observable query:string = ''
    // tab值
    @observable activeKey: string = '全部'

    // 根据query tab 动态获取展示todo
    @computed get todos() {
        this.loading = true;
        let todos = this.allTodos;
        if(this.activeKey) {
            switch(this.activeKey) {
                case '已完成':
                    todos = this.allTodos.filter(todo => todo.finished==true);
                    break;
                case '未完成':
                    todos = this.allTodos.filter(todo => todo.finished==false);
                    break;
                default:
                    todos = this.allTodos;
            }
        }
        if(this.query) {
            todos = todos.filter(todo => todo.text.includes(this.query));
        }
        this.loading = false;
        return todos;
    }

    // 设置活动tab
    @action.bound setActiveKey(key:string) {
        this.activeKey = key;
    }
    // 设置搜索关键词
    @action.bound onSetQuery(value:string) {
        this.query = value;
    }
    // 增加todo
    @action.bound onAdd(value:string) {
        this.allTodos = [
            ...this.allTodos,
            {
                id: this.allTodos.length+Math.random(),
                text: value,
                finished: false,
            }
        ]
    }
    // 删除某个todo
    @action.bound onDelete(id:number) {
        this.allTodos = this.allTodos.filter(todo => todo.id!== id)
    }
    // todo 状态改变 是否完成
    @action.bound onChange(id:number) {
        const idx = this.allTodos.findIndex(todo => todo.id == id);
        // this.allTodos = [...this.allTodos];
        this.allTodos[idx].finished = !this.allTodos[idx].finished;
    }
}

export default todoStore;